﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using hotel.Win.Common;
using hotel.DAL;
using hotel.Win.BaseData;
using hotel.Win.Subscribe;
using hotel.Common;
using hotel.MyUserControl;
using hotel.Win.Systems;
using System.Data.Entity;
namespace hotel.Win
{
    public partial class MainControl
    {
        private Dictionary<string,ucRoom> AllRoom;//所有房间控件 key =room_id value=ucRoom

      
        /// <summary>
        /// 建立列，表示的控件
        /// </summary>
        /// <returns></returns>
        private Label CreateColumnControl(string text)
        { 
            return new Label()
            {
                AutoSize = false,
                //BorderStyle = BorderStyle.Fixed3D,
                TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
                Text = text,
                Size = new System.Drawing.Size(UcRoomSet.GetUcRoomSet.Width, 23),
                Margin = new Padding(1, 0, 1, 0),
                BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(203)))), ((int)(((byte)(225)))), ((int)(((byte)(252)))))
            };
        }

        /// <summary>
        /// 建立行，表示的控件
        /// </summary>
        /// <returns></returns>
        private Label CreateRowControl(string text)
        {
            return new Label()
            {
                AutoSize = false,
                //BorderStyle = BorderStyle.Fixed3D,
                TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
                Text = text,
                Size = new System.Drawing.Size(40, UcRoomSet.GetUcRoomSet.Height),
                Margin=new Padding(0,1,0,1),
                BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(203)))), ((int)(((byte)(225)))), ((int)(((byte)(252)))))
            };
        }

        /// <summary>
        /// 房间双击事件回调
        /// </summary>
        private void RoomDoubleClickCallBack(ucRoom ucroom)
        {
           
            plnTootip.Visible = false;
            ROOM room = ucroom.Room;
           
            rzkrSelect selectFrm;
            //当预定选择时
            if (rbtnyd.Checked)
            {
                jddjFrm frm = null;
                using (var _context = MyDataContext.GetDataContext)
                {
                    var rzjls = _context.RZJL.AsNoTracking().Where(p => p.ROOM.ID == room.ID && p.YDBZ == "是").ToList();
                    if (rzjls.Count == 0)
                        frm = new jddjFrm(room.ID, 0);
                    else if (rzjls.Count == 1)
                        frm = new jddjFrm(rzjls.First().ID, 0, false);
                    else
                    {
                        selectFrm = new rzkrSelect(rzjls);
                        if (selectFrm.ShowDialog() != DialogResult.OK)
                            return;
                        frm = new jddjFrm(selectFrm.SelectedRZJL.ID, 0, false);
                    }
                }
                frm.ShowDialog();
                RefreshRoomFromDataBase(ucroom);
                if (frm.RoomIds != null)
                    RefreshRoomFromDataBase(frm.RoomIds);
            }
            else if (rbtnqt.Checked)
            {
                KRTJMenuMethod(ucroom);
                /*var rzjls = _context.RZJL.AsNoTracking().Where(p => p.ROOM.ID == room.ID && p.YDBZ == "否").ToList();
                //当前只有一个入住
                if (rzjls.Count == 0)
                    frm = new jddjFrm(room.ID, 1);
                else if (rzjls.Count == 1)
                    frm = new jddjFrm(rzjls.First().ID, 1, false);
                else
                {
                    selectFrm = new rzkrSelect(rzjls);
                    if (selectFrm.ShowDialog() != DialogResult.OK)
                        return;
                    frm = new jddjFrm(selectFrm.SelectedRZJL.ID, 1, false);
                }
                 */ 
            }
            else if (rbtnkf.Checked)
            {
                //空脏房直接修改成--空净房
                if (room.ZT == RoomStstusCnName.KongZang)
                {
                    try
                    {
                        using (var _context = MyDataContext.GetDataContext)
                        {
                            var croom = _context.ROOM.Find(room.ID);
                            //_context.Entry(room).State = EntityState.Modified;
                            croom.ZT = RoomStstusCnName.KongJing;
                            _context.SaveChanges();
                            RefreshRoomFromDataBase(ucroom);
                        }
                    }
                    catch (Exception ex)
                    {
                        var log = Log.Instance;
                        log.Abstract = LogAbstractEnum.未知;
                        log.Message = "空脏房修改成空净房时出错:" + ex.Message;
                        log.Error();
                        MessageBox.Show("空脏房修改成空净房时出错:" + ex.Message);
                        return;
                    }

                }
                else
                {
                    var frm = new ftMaintain(room.ID);
                    frm.ShowDialog();
                    RefreshRoomFromDataBase(room.ID);
                }
            }
        }

         /// <summary>
        /// 房间双击事件回调
        /// </summary>
        private void RoomClickCallBack(ucRoom ucroom)
        {
            var _context = MyDataContext.GetDataContext;
            txtfjh.Text = ucroom.Room.ID;
            currentURoom = ucroom;
            foreach (var item in AllRoom)
            {
                if (item.Value.Selected && txtfjh.Text != item.Key)
                {

                    item.Value.Selected = false;
                    item.Value.Refresh();

                }
            }

            #region 提示面板
            if (chkpop.Checked)
            {
                plnTootip.Visible = false;
                var rm = ucroom.Room;
                lbtooltipfjid.Text = "房间号:" + rm.ID;
                if (rm.RZBZ == "是")
                {
                    var rzjl = _context.RZJL.FirstOrDefault(p => p.ROOM.ID == rm.ID && p.RZBZ == "是");
                    if (rzjl == null)
                    {
                        MessageBox.Show("没有找到入住记录，房间状态有误！");
                        return;
                    }
                    gboxToolTip_kr.Visible = true;
                    gboxToolTip_fj.Visible = false;
                    var xm = "";
                    foreach (var item in _context.RZRY.Where(p => p.RZJL.ID == rzjl.ID))
                        xm += item.KRXM + " ";

                    lbtoolTip_xm.Text = "姓名：" + xm;
                    lbtoolTip_rs.Text = "人数：" + _context.RZRY.Count(p => p.RZJL.ID == rzjl.ID).ToString();
                    lbtoolTip_ddrq.Text = "抵店日期：" + rzjl.DDRQ.ToString();
                    lbtoolTip_ldrq.Text = "离店日期：" + rzjl.LDRQ.ToString();
                    var zf = _context.XFJL.Where(p => p.RZJL.ID == rzjl.ID).Sum(p => p.YJ);
                    var xf = _context.XFJL.Where(p => p.RZJL.ID == rzjl.ID).Sum(p => p.JE);
                    if (zf == null)
                        zf = 0;
                    if (xf == null)
                        xf = 0;
                    lbtoolTip_zf.Text = "支付：" + zf.ToString();
                    lbtoolTip_xf.Text = "消费：" +Math.Round((decimal)xf).ToString();
                    lbtoolTip_ye.Text = "余额：" + (zf - xf).ToString();
                }
                else
                {
                    gboxToolTip_fj.Visible = true;
                    gboxToolTip_kr.Visible = false;
                    lbtoolTip_fl.Text = "房类：" + rm.ROOM_TYPE.MC + "(" + rm.ROOM_TYPE.ID + ")";
                    lbtoolTip_fz.Text = "房租：" + rm.SKFJ.ToString();
                    lbtoolTip_cx.Text = "朝向：" + rm.CX;
                    lbtoolTip_cs.Text = "床数：" + rm.CS.ToString();
                    lbtoolTip_ms.Text = "描述：" + rm.FJMS;
                }
                Point formPoint = this.PointToClient(Control.MousePosition);
                formPoint.X = formPoint.X + 5;
                formPoint.Y = formPoint.Y + 5;
                plnTootip.Location = formPoint;
                plnTootip.Visible = true;
            }
            #endregion
            _context.Dispose();
        }
        /// <summary>
        /// 房间拖动事件成功后调用
        /// </summary>
        /// <param name="sourceRoomId"></param>
        /// <param name="targetRoomId"></param>
        private void RoomDragDropCallBack(string sourceRoomId, string targetRoomId)
        {
            if (sourceRoomId == targetRoomId)
                return;
            var _context = MyDataContext.GetDataContext;
            //目标房不能是在住，可以考虑当入住时实现关联房操作
            if (_context.RZJL.FirstOrDefault(p => p.ROOM.ID == targetRoomId && p.RZBZ == "是") != null)
            {
                MessageBox.Show("目标房间" + targetRoomId + "已经有人在住,不能换房");
                return;
            }
            var rzjls = _context.RZJL.Where(p => p.ROOM.ID == sourceRoomId);
            if (rzjls.Count() > 1)
            {
                MessageBox.Show("当房间只有一个有效帐号才能在房态图上拖动换房!请用右键菜单的换房功能!");
                return;
            }
            else if (rzjls.Count() == 0)
            {
                MessageBox.Show("该房间不具备换房条件!只有在住房和预订房才可以!");
                return;
            }

            var sourceRzjl = rzjls.First();
            var targetRoom = _context.ROOM.FirstOrDefault(p => p.ID == targetRoomId);
            var frm = new kyhfMaintain(sourceRzjl.ROOM.ID, (decimal)sourceRzjl.SJFJ, targetRoom.ID, (decimal)targetRoom.SKFJ);
            if (frm.ShowDialog() != DialogResult.OK)
                return;
            _context.Dispose();
            SaveKRHF(sourceRzjl.ID, frm.RoomId, frm.NewFJ,frm.YY);
            RefreshRoomFromDataBase(new List<string> { sourceRoomId, targetRoomId });
        }


        /// <summary>
        /// 刷新所有房间--强制从数据库
        /// </summary>
        public void RefreshAllRoom()
        {
            var tlpHouse1 = tabMain.SelectedTab.Controls[0] as TableLayoutPanel;
            tlpHouse1.SuspendLayout();
            foreach (var item in AllRoom)
            {
               //_context.Refresh(System.Data.Objects.RefreshMode.StoreWins,item.Value.Room);
               item.Value.RefreshRoom();
            }
            tlpHouse1.ResumeLayout(false);
        }

        /*
      private void CreateBuilding(TableLayoutPanel canvas, IQueryable<ROOM> houses)
      {
          if (AllRoom == null)
              AllRoom = new Dictionary<string, ucRoom>();
          else
              AllRoom.Clear();
          //填充到panel
          canvas.Controls.Clear();
          canvas.ColumnStyles.Clear();
          canvas.RowStyles.Clear();
          houses.OrderBy(p => p.ID);
          if (houses.Count() == 0)
              return;
          canvas.SuspendLayout();
          //本栋楼，单层最大房间数
          var maxRoomCnt = (from q in houses
                            group q by q.LC into g
                            select g).Max(p => p.Count());

          int maxFloorCnt = Convert.ToInt32(houses.Max(p => p.LC)); //最大楼层

          canvas.ColumnCount = maxRoomCnt + 2;//[0,0]为标题栏
          //多加一行和一列，好布局
          //创建横向（列）房间数
          var hcol = new ColumnStyle(SizeType.Absolute, 40);//与CreateRowControl,的width相同
          canvas.ColumnStyles.Add(hcol);
          for (int i = 0; i < maxRoomCnt+1; i++)
          {
              var colstyle = new ColumnStyle(SizeType.Absolute, ucRoom.MaxWidth);
              canvas.ColumnStyles.Add(colstyle);
          }
          //行，楼层
          canvas.RowCount = maxFloorCnt + 2;
          canvas.RowStyles.Add(new RowStyle(SizeType.Absolute, 23));//列标题栏
          for (int i = 0; i < maxFloorCnt +1; i++)
          {
              canvas.RowStyles.Add(new RowStyle(SizeType.Absolute, ucRoom.MaxHeight));
          }
          canvas.Size = new Size(maxRoomCnt * (ucRoom.MaxWidth + 2) + 26, maxFloorCnt * (ucRoom.MaxHeight + 2) + 23); 
          for (int i = 0; i < maxRoomCnt; i++)
          {
              canvas.Controls.Add(CreateColumnControl((i + 1).ToString().PadLeft(2, '0')), i + 1, 0);
          }
            
          for (int i = maxFloorCnt; i > 0; i--)
          {
              canvas.Controls.Add(CreateRowControl((i).ToString().PadLeft(2, '0') + "/F"), 0, maxFloorCnt - i + 1);
          }
          //创建房间
          string lc = "0";
          for (int f = maxFloorCnt; f > 0; f--)
          {
              int col = 1;
              lc = f.ToString();
              foreach (var h in houses.Where(p => p.LC == lc).OrderBy(p => p.ID))
              {
                  var uc = new ucRoom(h);
                  uc.DoubleClickCallBack = RoomDoubleClickCallBack;
                  uc.DragDropCallBack = RoomDragDropCallBack;
                  uc.ClickCallBack = RoomClickCallBack;
                  uc.SetContextMenu(this.contextMenuRoom);
                  uc.Dock = DockStyle.Fill;
                  canvas.Controls.Add(uc, col, maxFloorCnt - f + 1);
                  AllRoom.Add(h.ID, uc);
                  col++;
              }
          }
            
          canvas.ResumeLayout();
         
      }
       */

    }
}
